package com.tangtang.mvc.controller;

import com.tangtang.security.MyUserDetails;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    protected MyUserDetails getUserDetails() {
        MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDetails;
    }


    /**
     * @return
     */
    protected ModelAndView view(String viewFilePath) {
        return view(viewFilePath, null, null, new String[0]);
    }

    /**
     * @param success
     * @param message
     * @return
     */
    protected ModelAndView view(String viewFilePath, boolean success, String... message) {
        return view(viewFilePath, null, success, message);
    }

    protected ModelAndView view(String viewFilePath, Object model, Boolean success, String... message) {
        ModelAndView view = new ModelAndView(viewFilePath);
        view.addObject("from", request.getServletPath());
        if (success != null) {
            view.addObject("success", success);
        }
        if (message != null && message.length > 0) {
            view.addObject("message", message);
        }
        if (model != null) {
            view.addObject("command", model);
        }
        return view;
    }

    /**
     * @param viewFilePath
     * @param model
     * @return
     */
    protected ModelAndView view(String viewFilePath, Object model) {
        return view(viewFilePath, model, null, new String[0]);
    }
}
